//
//  NewFeatureView.swift
//  微博Swift
//
//  Created by  justinchou on 16/2/26.
//  Copyright © 2016年  justinchou. All rights reserved.
//

import UIKit
import SnapKit

/// 新特性界面图片数量
private let JustinNewFeatureImageCount = 4

class NewFeatureView: UIView {

    override init(frame: CGRect) {
        super.init(frame: UIScreen.mainScreen().bounds)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- 懒加载控件
    private lazy var pageControl = UIPageControl()

}

// MARK:- 设置界面
extension NewFeatureView {
    
    func setupUI() {
        
        // MARK:- 设置scrollView
        let scrollView = UIScrollView(frame: bounds)
        addSubview(scrollView)
        
        scrollView.delegate = self
        
        for i in 0..<JustinNewFeatureImageCount {
            
            let iv = UIImageView(image: UIImage(named: "new_feature_\(i + 1)"))
            iv.frame = CGRectOffset(bounds, CGFloat(i) * bounds.width, 0)
            scrollView.addSubview(iv)
        }
        
        //为何加一 实现拖到最后一个图片的时候就直接显示主页内容
        scrollView.contentSize = CGSize(width: CGFloat(JustinNewFeatureImageCount + 1) * bounds.width, height: 0)
        
        scrollView.pagingEnabled = true
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        
        // MARK:- 设置pagecontroller
        addSubview(pageControl)
        pageControl.currentPage = 0
        pageControl.numberOfPages = 4
        //pagecontrol可以被点击 ，为了效果取消交互
        pageControl.userInteractionEnabled = false
        //设置pagecontroll的颜色
        pageControl.currentPageIndicatorTintColor = UIColor.orangeColor()
        pageControl.pageIndicatorTintColor = UIColor.darkGrayColor()
        
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(self).offset(-80)
        }
    
    }
}

// MARK:- 代理方法的实现
extension NewFeatureView:UIScrollViewDelegate {
    
    func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        //当滚动到最后一页的时候，直接将新特性界面移除
        let page = Int(scrollView.contentOffset.x / bounds.width)
        print("\(page)")
        if page == JustinNewFeatureImageCount - 1 {
            removeFromSuperview()
        }
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
        let page = Int(scrollView.contentOffset.x / bounds.width + 0.5)
        
        pageControl.currentPage = page
        
        if page == JustinNewFeatureImageCount {
            pageControl.hidden = true
        }
    }
}







